package com.kejiguan.ui;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;

import com.kejiguan.ui.adapter.SheduleObjectAdapterNew;
import com.kejiguan.ui.adapter.SheduleOperationAdapter;
import com.kejiguan.ui.adapter.SheduleTimeTypeAdapter;
import com.kejiguan.ui.adapter.SheduleWeekAdapter;
import com.kejiguan.ui.adapter.TimeSpinnerAdapter;
import com.kejiguan.ui.model.DisplayArea;
import com.kejiguan.ui.model.ExhibitionNeItem;
import com.kejiguan.ui.model.Shedule;
import com.kejiguan.ui.model.SheduleActionType;
import com.kejiguan.ui.model.SheduleObject;
import com.kejiguan.ui.model.SheduleTypeModel;
import com.kejiguan.ui.model.WeekItem;
import com.kejiguan.ui.presenter.TimeSheduleActivityPresenter;
import com.kejiguan.ui.response.AddSheduleResponse;
import com.kejiguan.ui.util.CacheDataUtil;
import com.kejiguan.ui.util.CommonDate;
import com.kejiguan.ui.widget.NoScrollGridView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by YYY on 16/8/16.
 */
public class AddTimingScheduleActivity extends Activity implements View.OnClickListener {

    private TimeSheduleActivityPresenter mPresenter;

    private EditText sheduleNameInput;
    private Spinner sheduleTypeSpinner;
    private Spinner weekSpinner;

    private Spinner hourSpinner, minSpinner, secSpinner;
    private Spinner sheduleActionSpinner;
    private NoScrollGridView sheduleObjectList;
    private View addBtn, cancelBtn;

    private List<SheduleObject> sheduleObjects=new ArrayList<>(0);
    private String selectObjectIds;
    private SheduleObjectAdapterNew sheduleObjectAdapter;

    @Override
    public void onCreate(Bundle bundle) {
        super.onCreate(bundle);

        mPresenter=new TimeSheduleActivityPresenter();
        mPresenter.onCreate(AddTimingScheduleActivity.this);
        setContentView(R.layout.activity_add_timing_shedule_layout);
        EventBus.getDefault().register(this);
        initSelectObjectsBySelectIds();
        initViews();
    }




    @Override
    public void onDestroy()
    {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    private void initSelectObjectsBySelectIds()
    {
        sheduleObjects.clear();

        if (TextUtils.isEmpty(selectObjectIds))
        {
            SheduleObject sheduleObject=new SheduleObject();
            sheduleObject.setId("");
            sheduleObject.setName("新增");

            sheduleObjects.add(sheduleObject);
        }else
        {

            if (selectObjectIds.contains("ZALL"))
            {
                SheduleObject sheduleObject=new SheduleObject();
                sheduleObject.setId("ZALL");
                sheduleObject.setName("全部");

                sheduleObjects.add(sheduleObject);
            }else
            {
                List<DisplayArea> displayAreas = CacheDataUtil.getInstance().getDisplayAreas();

                for (DisplayArea displayArea:displayAreas)
                {
                    if (selectObjectIds.contains(displayArea.getDisplayId()))
                    {

                        SheduleObject sheduleObject=new SheduleObject();
                        sheduleObject.setId(displayArea.getDisplayId());
                        sheduleObject.setName(displayArea.getDisplayName());

                        sheduleObjects.add(sheduleObject);
                    }else
                    {
                        if (null!=displayArea.getExhibitionNeItems())
                        {
                            for (ExhibitionNeItem exhibitionNeItem:displayArea.getExhibitionNeItems())
                            {
                                if (selectObjectIds.contains(exhibitionNeItem.getExhibitionId()))
                                {
                                    SheduleObject sheduleObject=new SheduleObject();
                                    sheduleObject.setId(exhibitionNeItem.getExhibitionId());
                                    sheduleObject.setName(exhibitionNeItem.getExhibitionName());

                                    sheduleObjects.add(sheduleObject);
                                }
                            }
                        }
                    }
                }
            }

        }
    }

    private void initViews() {

        sheduleNameInput = (EditText) findViewById(R.id.shedule_name_input);
        sheduleTypeSpinner = (Spinner) findViewById(R.id.type_select);
        weekSpinner = (Spinner) findViewById(R.id.week_select);
        hourSpinner = (Spinner) findViewById(R.id.hour_select);
        minSpinner = (Spinner) findViewById(R.id.min_select);
        secSpinner = (Spinner) findViewById(R.id.sec_select);
        sheduleActionSpinner = (Spinner) findViewById(R.id.action_select);
        sheduleObjectList = (NoScrollGridView) findViewById(R.id.object_select);
        addBtn = findViewById(R.id.add_shedule_confirm_btn);
        cancelBtn = findViewById(R.id.add_shedule_cancel_btn);
        addBtn.setOnClickListener(this);
        cancelBtn.setOnClickListener(this);

        sheduleTypeSpinner.setPopupBackgroundResource(R.drawable.spinner_drawable);
        weekSpinner.setPopupBackgroundResource(R.drawable.spinner_drawable);
        hourSpinner.setPopupBackgroundResource(R.drawable.spinner_drawable);
        minSpinner.setPopupBackgroundResource(R.drawable.spinner_drawable);
        secSpinner.setPopupBackgroundResource(R.drawable.spinner_drawable);
        sheduleActionSpinner.setPopupBackgroundResource(R.drawable.spinner_drawable);

        hourSpinner.setAdapter(new TimeSpinnerAdapter(AddTimingScheduleActivity.this, 0, 23));
        minSpinner.setAdapter(new TimeSpinnerAdapter(AddTimingScheduleActivity.this, 0, 59));
        secSpinner.setAdapter(new TimeSpinnerAdapter(AddTimingScheduleActivity.this, 0, 59));
        sheduleActionSpinner.setAdapter(new SheduleOperationAdapter(AddTimingScheduleActivity.this, CommonDate.actionTypes));
        weekSpinner.setAdapter(new SheduleWeekAdapter(AddTimingScheduleActivity.this, CommonDate.weekItems));
        sheduleTypeSpinner.setAdapter(new SheduleTimeTypeAdapter(AddTimingScheduleActivity.this, CommonDate.sheduleTypeModels));
        sheduleTypeSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

                Log.e(AddTimingScheduleActivity.class.getSimpleName(), "position:" + position);
                if (position == (sheduleTypeSpinner.getAdapter().getCount() - 1)) {
                    weekSpinner.setVisibility(View.VISIBLE);
                } else {
                    weekSpinner.setVisibility(View.GONE);
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        sheduleObjectAdapter=new SheduleObjectAdapterNew(AddTimingScheduleActivity.this,sheduleObjects,AddTimingScheduleActivity.this);
        sheduleObjectList.setAdapter(sheduleObjectAdapter);
    }


    @Override
    public void onClick(View v) {
        switch (v.getId())
        {
            case R.id.add_shedule_confirm_btn:

                String sheduleName = sheduleNameInput.getText().toString();
                if (TextUtils.isEmpty(sheduleName)) {
                    Toast.makeText(AddTimingScheduleActivity.this, "任务名不能为空", Toast.LENGTH_SHORT).show();
                    break;
                }

                SheduleTimeTypeAdapter sheduleTimeTypeAdapter = (SheduleTimeTypeAdapter) sheduleTypeSpinner.getAdapter();
                String timeType = ((SheduleTypeModel) sheduleTimeTypeAdapter.getItem(sheduleTypeSpinner.getSelectedItemPosition())).getTypeId();
                if ("5".equals(timeType)) {
                    SheduleWeekAdapter weekAdapter = (SheduleWeekAdapter) weekSpinner.getAdapter();
                    String weekType = ((WeekItem) weekAdapter.getItem(weekSpinner.getSelectedItemPosition())).getWeekId();
                    timeType = timeType + "," + weekType;
                }

                SheduleOperationAdapter operationAdapter = (SheduleOperationAdapter) sheduleActionSpinner.getAdapter();
                String actionType = ((SheduleActionType) operationAdapter.getItem(sheduleActionSpinner.getSelectedItemPosition())).getActionId();

                int hour = hourSpinner.getSelectedItemPosition();
                int min = minSpinner.getSelectedItemPosition();
                int sec = secSpinner.getSelectedItemPosition();

                String hourS = hour < 10 ? "0" + hour : String.valueOf(hour);
                String minS = min < 10 ? "0" + min : String.valueOf(min);
                String secS = sec < 10 ? "0" + sec : String.valueOf(sec);

                if(TextUtils.isEmpty(selectObjectIds))
                {
                    Toast.makeText(AddTimingScheduleActivity.this,"请选择定时任务调度对象",Toast.LENGTH_SHORT).show();
                    break;
                }else {
                    if (selectObjectIds.endsWith(","))
                    {
                        selectObjectIds=selectObjectIds.substring(0,selectObjectIds.length()-1);
                    }
                }

                Shedule shedule = new Shedule();
                shedule.setScheduleName(sheduleName);
                shedule.setScheduleType(timeType);
                shedule.setScheduleAction(actionType);
                shedule.setScheduleObject(selectObjectIds);
                shedule.setScheduleNote("");
                shedule.setScheduleTime(hourS + ":" + minS + ":" + secS);
                shedule.setScheduleState("0");

                mPresenter.addShedule(shedule);

                break;
            case R.id.add_shedule_cancel_btn:
                finish();
                break;
            case R.id.object_name:
                Intent selectObjectIntent=new Intent(AddTimingScheduleActivity.this,SelectSheduleObjectActivity.class);
                Bundle bundle=new Bundle();
                bundle.putString("selectIds",selectObjectIds);
                selectObjectIntent.putExtras(bundle);
                startActivityForResult(selectObjectIntent,99);
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent)
    {
        if (resultCode==RESULT_OK)
        {
            switch (requestCode)
            {
                case 99:
                    String result=intent.getStringExtra("selectIds");
                    selectObjectIds=new String(result);
                    initSelectObjectsBySelectIds();
                    sheduleObjectAdapter.notifyDataSetChanged();
                    break;
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(AddSheduleResponse response) {

        if ("0000".equals(response.getRetCode())) {

            Toast.makeText(AddTimingScheduleActivity.this,"新增定时任务成功",Toast.LENGTH_SHORT).show();
            finish();
        }else
        {
            Toast.makeText(AddTimingScheduleActivity.this,response.getRetInfo(),Toast.LENGTH_SHORT).show();
        }
    }


}
